package com.coc.ofhibernate.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * 主数据源配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages={"com.coc.ofhibernate.repository.main","com.coc.ofhibernate.dao"}   // 配置 repository的包位置
//        basePackageClasses = {MainRepository.class}
)

public class PrimaryConfig {
//
//    @Autowired
//    private Environment env;

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;// 自动注入配置好的数据源


    @Bean("entityManagerFactoryPrimary")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(primaryDataSource);
        factory.setPackagesToScan("com.coc.ofhibernate.entity.database1");  // 实体类的位置
        factory.setJpaVendorAdapter(vendorAdapter);
        return factory;

    }

    @Bean("transactionManagerPrimary")
    @Primary
    public PlatformTransactionManager transactionManagerPrimary() {
        EntityManagerFactory factory = entityManagerFactoryPrimary().getObject();
        return new JpaTransactionManager(factory);
    }

    /**
     *  .yml initialize: true   初始化 执行sql
     */
//    @Bean
//    public DataSourceInitializer manDataSourceInitializer() {//6
//        DataSourceInitializer dsInitializer = new DataSourceInitializer();
//        dsInitializer.setDataSource(manDataSource());
//        ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
//        dbPopulator.addScript(new ClassPathResource("security-data.sql"));
//        dsInitializer.setDatabasePopulator(dbPopulator);
//        dsInitializer.setEnabled(env.getProperty("datasource.man.initialize",
//                Boolean.class, false) );
//        return dsInitializer;
//    }


}
